package com.generator.service.impl;

import com.generator.domain.custom.Organization;
import com.generator.domain.custom.Storehouse;
import com.generator.domain.Table;
import com.generator.service.StoreLabelService;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-9-27
 * Time: 下午4:23
 * To change this template use File | Settings | File Templates.
 */
@Service("storeLabelService")
public class StoreLabelServiceImpl implements StoreLabelService {

    /**
     * 生成库房标签HTML
     *
     * @param xlsPath  XLS配置文件
     * @param htmlPath HTML文件
     */
    @Override
    public void storeLabelToHtml(String xlsPath, String htmlPath) {
        try {
            List<Organization> orgs = readConfigXls(xlsPath);
            System.out.println(orgs.size());
            Map<String, Object> ftl_params = new HashMap<String, Object>();
            ftl_params.put("orgs", orgs);
            ftl_params.put("date", new Date());
            initHtmlFreemarker(ftl_params, htmlPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initHtmlFreemarker(Map<String, Object> params, String htmlPath) {

        try {
            /* 在整个应用的生命周期中，这个工作你应该只做一次。 */
            /* 创建和调整配置。 */
            Configuration cfg = new Configuration();
            File templatePath = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "ftl");
            cfg.setDirectoryForTemplateLoading(templatePath);
            // 编码设置1
            cfg.setDefaultEncoding("UTF-8");
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            /* 在整个应用的生命周期中，这个工作你可以执行多次 */
            /* 获取或创建模板*/
            Template temp = cfg.getTemplate("html.ftl");
            // 编码设置2
            temp.setEncoding("UTF-8");
            Table table = (Table) params.get("table");

            File file = new File(htmlPath);

            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));

            /* 将模板和数据模型合并 */
            //Writer out = new OutputStreamWriter(System.out);
            temp.process(params, out);
            //out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<Organization> readConfigXls(String xlsPath) throws Exception {
        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(xlsPath));
        Sheet sheet = wb.getSheetAt(0);
        int rowLen = sheet.getLastRowNum();

        List<Organization> orgs = new ArrayList<Organization>();

        for (int i = 1; i < rowLen; i++) {
            Row row = sheet.getRow(i);
            String orgName = getValue(row.getCell(0));
            String orgCode = getValue(row.getCell(5));
            String storeName = getValue(row.getCell(1));
            String storeType = getValue(row.getCell(2));
            String storeAppIP = getValue(row.getCell(3));
            String storeDbIP = getValue(row.getCell(4));
            String storeCode = getValue(row.getCell(6));

            Organization org = null;
            for (Organization item : orgs) {
                if (orgName.equals(item.getName())) {
                    org = item;
                    break;
                }
            }

            if (org == null) {
                org = new Organization();
                org.setName(orgName);
                org.setCode(orgCode);
                orgs.add(org);
            }
            Storehouse store = new Storehouse();
            store.setName(storeName);
            store.setType(storeType);
            store.setCode(storeCode);
            store.setAppIP(storeAppIP);
            store.setDbIP(storeDbIP);
            org.getStorehouses().add(store);
        }
        return orgs;
    }

    private String getValue(Cell cell) {
        String value = "";
        switch (cell.getCellType()) {
            case 1:
                value = cell.getStringCellValue();
                break;
            case 0:
                value = ((int)cell.getNumericCellValue()) + "";
                break;
            default:
                value = cell.getStringCellValue();
        }
        return value;
    }

}
